<template>
  <div class="app-container">
    <!-- 工具栏 start-->
    <div class="nav-tool">
      <div class="nt-main"></div>
      <div class="nt-aside">
        <el-button
          size="small"
          class="btnRouter"
          type="primary"
          @click="handleAction(null, 'new')"
        >创建角色</el-button>
      </div>
    </div>
    <!-- 工具栏 end-->

    <div class="page-content">
      <el-table
        ref="table"
        v-loading="loading"
        :data="lists"
        :height="st"
        style="width: 100%"
        row-key="id"
        lazy
        :tree-props="{ hasChildren: 'subOrder' }"
      >
        <el-table-column label="角色id" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.type_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否显示" width="110" align="center">
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.is_action == 0"
              disabled
              v-model="scope.row.state"
              :active-value="1"
              :inactive-value="0"
            />
            <el-switch
              v-auth="'/admin/auth/role/action'"
              v-if="scope.row.is_action != 0"
              v-model="scope.row.state"
              :active-value="1"
              :inactive-value="0"
              @change="settingState(scope.row)"
            />
            <el-switch
              v-no-auth="'/admin/auth/role/settingState'"
              v-if="scope.row.is_action != 0"
              disabled
              v-model="scope.row.state"
              :active-value="1"
              :inactive-value="0"
              @change="settingState(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="230" align="center">
          <template slot-scope="scope">
            <el-button
              v-auth="'/admin/auth/role/action'"
              v-if="scope.row.is_action == 1"
              type="text"
              size="mini"
              @click="handleAction(scope.row)"
            >编辑</el-button>
            <el-button
              v-auth="'/admin/auth/role/delete'"
              v-if="scope.row.is_action == 1"
              type="text"
              size="mini"
              @click="handleDel(scope.row)"
            >删除</el-button>
            <el-button
              v-auth="'/admin/auth/role/saveAuth'"
              v-if="scope.row.is_action == 1"
              type="text"
              size="mini"
              @click="handleAuth(scope.row)"
            >修改权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        ref="paginationTotal"
        :page="currentPage"
        :total="total"
        :size="pageSize"
        @sizeChange="sizeChange"
        @currentChange="currentChange"
      />
    </div>

    <!--弹框-->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :before-close="modalClose"
      :close-on-press-escape="false"
      append-to-body
    >
      <div v-loading="loading">
        <el-form :model="actionForm" ref="actionForm" label-width="150px" size="small">
          <el-form-item label="角色名称：" prop="name" :rules="$rule.required">
            <el-input v-model.trim="actionForm.name" />
          </el-form-item>
          <el-form-item label="是否显示：" prop="state" :rules="$rule.required">
            <el-radio v-model="actionForm.state" :label="1">是</el-radio>
            <el-radio v-model="actionForm.state" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="type" label="类型：" :rules="$rule.required" align="left">
            <template v-for="(item, index) in dict_list.type_list">
              <el-radio v-model="actionForm.type" :label="item.value">{{ item.label }}</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <div class="tool2">
          <el-button @click="handleSubmit" type="primary" size="medium">确定</el-button>
          <el-button @click="modalClose" size="medium">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogAuthVisible"
      title="权限修改"
      :before-close="modalAuthClose"
      :close-on-press-escape="false"
      append-to-body
    >
      <div v-loading="dialogAuthLoading">
        <el-tree
          ref="authTree"
          show-checkbox
          :data="dict_list.menu_list"
          :props="defaultProps"
          default-expand-all
          node-key="id"
          :expand-on-click-node="false"
          class="authDialog"
        ></el-tree>
        <div class="tool2">
          <el-button @click="handleSubmitAuth" type="primary" size="medium">确定</el-button>
          <el-button @click="modalAuthClose" size="medium">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      lists: [],
      dialogloading: true,
      loading: false,

      // 默认显示第几页
      currentPage: 1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      total: 0,
      // 个数选择器（可修改）
      pageSizes: [50, 100, 200],
      // 默认每页显示的条数（可修改）
      pageSize: 30,

      st: 0,
      keyword: null,
      dialogVisible: false,
      dialogTitle: '创建账号',

      suppliers: [],

      created_at: [],
      last_examine_time: [],

      searchParams: {},

      actionForm: {
        id: '', // ID值【更新时必填】
        name: '',
        state: '',
        type: '',
      },

      dialogAuthVisible: false,
      dialogAuthLoading: true,

      dict_list: {},

      checked: false,

      role_id: 0,
      role_type: 0,

      // 数据默认字段
      defaultProps: {
        parent: 'pid', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'title', // 标签显示
        children: 'child', // 子级
        disabled: this.menuDisable, // 子级
      },
    }
  },
  created() {
    this.handleInit()
  },

  mounted() {
    const that = this
    that.$util.autoHeight(that, that.$refs.table.$el)
  },
  methods: {
    reseting(o = {}) {
      o = { lists: [], ...o }
      this.$util.setAttr(this, o)
    },

    // 关闭对话框
    modalClose() {
      this.dialogVisible = false
    },

    // 设置状态
    async settingState(row) {
      const that = this
      try {
        const data = { id: row.id }
        that.dialogloading = true
        const { result } = await that.$.authority.roleSettingState(data)
        that.dialogloading = false
        that.dialogVisible = false
        that.$message({ type: 'success', message: '修改成功' })
      } catch (e) {
        that.dialogloading = false
      }
    },

    // 搜索
    handleSearch(statu) {
      this.currentPage = 1
      this.handleRequest()
    },

    sizeChange(e) {
      const that = this
      that.currentPage = 1
      that.pageSize = e
      that.handleRequest()
    },

    currentChange(e) {
      this.currentPage = e
      this.handleRequest()
    },

    async handleRequest() {
      const that = this
      const { currentPage, pageSize } = that

      that.searchParams.page_size = pageSize
      that.searchParams.page = currentPage

      try {
        that.loading = true
        const { result } = await that.$.authority.authRoleIndex(
          that.searchParams
        )
        that.total = result.pagination.total_count
        that.$refs.table.bodyWrapper.scrollTop = 0
        that.lists = result.list
        that.loading = false
      } catch (e) {
        that.loading = false
      }
    },

    async handleInit() {
      const that = this
      that.handleRequest()
    },

    // 新建，编辑标签
    async handleAction(row = null) {
      const that = this

      that.loading = true

      if (JSON.stringify(that.dict_list) === '{}') {
        const { result } = await that.$.authority.authRoleDict()
        that.dict_list = result
      }

      that.loading = false

      if (row === null) {
        this.dialogTitle = '创建角色'

        this.actionForm.id = ''
        this.actionForm.name = ''
        this.actionForm.state = 1
        this.actionForm.type = 3
      } else {
        this.dialogTitle = '编辑角色'

        this.actionForm.id = row.id
        this.actionForm.name = row.name
        this.actionForm.state = row.state
        this.actionForm.type = row.type
      }

      this.dialogVisible = true
    },

    //保存
    handleSubmit() {
      let that = this
      that.$refs.actionForm.validate(async (v) => {
        if (!v) {
          return false
        }
        try {
          that.dialogloading = true
          let { result } = await that.$.authority.authRoleIAction(
            that.actionForm
          )
          that.dialogloading = false
          that.dialogVisible = false
          that.$message({ type: 'success', message: '保存成功' })
          that.handleRequest()
        } catch (e) {
          that.dialogloading = false
        }
      })
    },

    // 删除
    async handleDel(e) {
      let that = this
      let ask = await that.$util.confirm({ that, content: `确定删除?` })
      if (ask) {
        let { result } = await that.$.authority.authRoleDelete({
          selected: e.id,
        })
        that.$message({ type: 'success', message: '删除成功' })
        that.handleRequest()
      }
    },

    // 查看权限
    async handleAuth(row) {
      let that = this
      that.dialogAuthLoading = true

      if (JSON.stringify(that.dict_list) === '{}') {
        const { result } = await that.$.authority.authRoleDict()
        that.dict_list = result
      }

      const { result } = await that.$.authority.authRoleInfo({ id: row.id })

      that.role_id = row.id

      that.role_type = row.type

      that.dialogAuthLoading = false
      that.dialogAuthVisible = true

      //设置选择值
      that.$data.thisRefTree = setInterval(() => {
        //清空
        this.$refs.authTree.setCheckedKeys([])

        //回显
        if (result.menu_ids != null) {
          result.menu_ids.forEach((i) => {
            let node = this.$refs.authTree.getNode(i)
            console.log('none', node)
            if (node && node.isLeaf) {
              this.$refs.authTree.setChecked(node, true)
            }
          })
        }
        clearInterval(that.$data.thisRefTree)
      }, 200)
    },

    // 关闭对话框
    modalAuthClose() {
      this.dialogAuthVisible = false
    },

    //保存权限
    async handleSubmitAuth() {
      let that = this

      //获取选择菜单id （包括父级）
      let ids = []
      const checkedNodes = this.$refs.authTree.getCheckedNodes(false, true)
      checkedNodes.forEach((item) => {
        ids.push(item.id)
      })

      let data = {
        role_id: that.role_id,
        menu_ids: ids,
      }

      try {
        that.dialogAuthVisible = true
        let { result } = await that.$.authority.authRoleSaveAuth(data)
        that.dialogAuthVisible = false
        that.dialogAuthVisible = false
        that.$message({ type: 'success', message: '保存成功' })
        that.handleRequest()
      } catch (e) {
        that.dialogAuthVisible = false
      }
    },

    //控制菜单能否选择
    menuDisable(row) {
      if (this.role_type === 2 && row.menu_type !== 2) {
        //外部角色，则需要控制不允许勾选
        return true
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.authDialog {
  height: 60vh;
  overflow: auto;
}
</style>
